import Taro, {getCurrentInstance} from "@tarojs/taro";
import COS from 'cos-wx-sdk-v5';
import {query} from "@/chaos/functions/Data";

export async function login() {
  const response = await Taro.login();
  if (response.errMsg === "login:ok") return response.code;
}

export async function getImageInfo(src) {
  return new Promise((reslove) => {
    Taro.getImageInfo({
      src, success: ({width, height}) => reslove({width, height}),
    });
  });
}

export function userProfile() {
  return new Promise((reslove) => {
    Taro.getUserProfile({
      desc: "用于完善会员资料", success: (res) => reslove(res.userInfo), fail: () => reslove(),
    });
  });
}

export function location() {
  return new Promise((reslove) => {
    Taro.getLocation({
      type: "gcj02", success: (res) => reslove(res), fail: () => reslove(),
    });
  });
}

export function get(key) {
  return Taro.getStorageSync(key);
}

export function successToast(title) {
  Taro.showToast({title});
}

export function failToast(title) {
  Taro.showToast({
    icon: "none", image: "/app/asserts/fail.png", title,
  });
}

export function infoToast(title) {
  Taro.showToast({icon: "none", title});
}

export function showLoading() {
  Taro.showLoading({title: "加载中"});
}

export function hideLoading() {
  Taro.hideLoading();
}

export async function navigateTo(url, params = "") {
  await Taro.navigateTo({url: path(url) + (params && "?") + params});
}


export async function navigateBack(delta = 1) {
  await Taro.navigateBack({delta});
}

export async function redirectTo(url, params = "") {
  await Taro.redirectTo({url: path(url) + (params && "?") + params});
}

export async function reLaunch(url) {
  await Taro.reLaunch({url: path(url)});
}

export function path(url) {
  return `/app/pages/${url}/index`;
}

export function barTitle(title) {
  Taro.setNavigationBarTitle({title});
}

export function message(tmplId) {
  return new Promise((reslove) => {
    Taro.requestSubscribeMessage({
      tmplIds: [tmplId], success: (res) => reslove(res),
    });
  });
}

export function getParams() {
  return getCurrentInstance().router.params;
}


const cos = new COS({
  getAuthorization: async (_, callback) => {
    const {credentials, startTime, expiredTime} = await query(
      'api/cos/getCredential'
    );
    callback({
      TmpSecretId: credentials.tmpSecretId,
      TmpSecretKey: credentials.tmpSecretKey,
      XCosSecurityToken: credentials.sessionToken,
      StartTime: startTime,
      ExpiredTime: expiredTime
    });
  }
});

export async function postObject(filename, filePath) {
  return new Promise(reslove => {
    cos.postObject(
      {
        Bucket: '',
        Region: '',
        Key: new Date().getTime() + '-' + filename,
        FilePath: filePath,
        onProgress: ({speed}) => {
          if (speed === 0) {
          }
        }
      },
      (err, data) => reslove({err, data})
    );
  });
}
